<template>
  <div class="search-suggestion">
    <van-cell @click="$emit('search',item)" v-for="(item,index) in list"  :key="index"  icon="search">
      <div slot="title" v-html="reverseStr(item)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSuggestionData } from '@/api/search';
import lodash from 'lodash'
// loadsh.debounce(function(){ 要做的事情 },事件)===> 返回还是一个函数！
export default {
  name: 'SearchSuggestion',
  props:{
    searchText:{
      type:String
    }
  },
  data () {
    return {
      list:[] // 搜索建议
    }
  },
  watch:{
    // searchText(){}
    searchText:{
      // 监听函数
      // async handler(){
          // if(this.timer) clearInterval(this.timer)
          // this.timer =  setTimeout(async () => {
          //   let { data } = await getSuggestionData({
          //     q:this.searchText
          //   })
          //   this.list = data.data.options
          // }, 2000);
      // },
      // handler:function(){},
      handler:lodash.debounce(function(value){
        this.loadSearchSuggestions(value)
      },200),
      deep:false, // 是否深监听
      immediate:true // 是否一开始就执行一次
    }
  },
  methods: {
    // 获取搜索建议
    async loadSearchSuggestions(val){
      let { data } = await getSuggestionData({
        q:val
      })
      this.list = data.data.options
    },
    // 字符串高亮处理
    reverseStr(val){
      try {
        return val.replaceAll(this.searchText,`<span style="color:red">${this.searchText}</span>`)
      } catch (error) {
        return 'null'
      }
    }
  }
}
</script>

<style scoped lang="less"></style>